from django.core.management.base import BaseCommand
from django.conf import settings
from projects.models import Webhook

class Command(BaseCommand):
    help = '更新所有Webhook的URL为正确的格式，并显示详细信息以便测试'

    def handle(self, *args, **options):
        # 获取所有Webhook
        webhooks = Webhook.objects.all()
        updated_count = 0
        
        # 使用项目设置中的实际域名
        base_url = settings.SITE_DOMAIN
        
        self.stdout.write(self.style.NOTICE('开始更新Webhook URL...'))
        self.stdout.write(self.style.NOTICE(f'使用的基础域名: {base_url}'))
        
        for webhook in webhooks:
            project = webhook.project
            # 生成项目slug
            project_slug = project.name.lower().replace(' ', '-')[:20]
            
            # 生成正确的URL格式 - 确保末尾有斜杠，与URL配置匹配
            correct_url = f"{base_url}/webhooks/{project_slug}/{webhook.id}/receive/"
            
            # 显示详细信息
            self.stdout.write(self.style.NOTICE(f'项目名称: {project.name}'))
            self.stdout.write(self.style.NOTICE(f'项目ID: {project.id}'))
            self.stdout.write(self.style.NOTICE(f'生成的项目slug: {project_slug}'))
            self.stdout.write(self.style.NOTICE(f'Webhook ID: {webhook.id}'))
            
            # 如果URL不匹配，更新它
            if webhook.url != correct_url:
                self.stdout.write(self.style.WARNING(f'旧URL: {webhook.url}'))
                webhook.url = correct_url
                webhook.save()
                updated_count += 1
                self.stdout.write(self.style.SUCCESS(f'新URL: {correct_url}'))
            else:
                self.stdout.write(self.style.SUCCESS(f'URL已经正确: {correct_url}'))
            
            self.stdout.write(self.style.NOTICE('---'))
        
        self.stdout.write(self.style.SUCCESS(f'Webhook URL批量更新完成！共更新了 {updated_count} 个Webhook'))
        
        # 提供测试命令示例
        if webhooks.exists():
            sample_webhook = webhooks.first()
            sample_project = sample_webhook.project
            sample_project_slug = sample_project.name.lower().replace(' ', '-')[:20]
            self.stdout.write(self.style.SUCCESS('\n测试命令示例:'))
            self.stdout.write(self.style.SUCCESS(f'python -m requests.post "{base_url}/webhooks/{sample_project_slug}/{sample_webhook.id}/receive/" -H "Content-Type: application/json" -d "{{\"test\": true}}"'))